package com.lei.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

/**
 * @author Lei Chu
 * @Date 2020/10/15 17:46
 */
public class BaseDb {

    private static DruidDataSource druidDataSource;

    static {
        try {
            InputStream inputStream = BaseDb.class.getClassLoader().getResourceAsStream("com/lei/druid-config.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            druidDataSource = new DruidDataSource();
            // 常规设置
            druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
            druidDataSource.setUrl(properties.getProperty("jdbcUrl"));
            druidDataSource.setUsername(properties.getProperty("db.username"));
            druidDataSource.setPassword(properties.getProperty("db.password"));
            // 初始化连接数
            druidDataSource.setInitialSize(Integer.parseInt(properties.getProperty("initialSize")));
            // 最大连接数
            druidDataSource.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
            // 等待超时时间
            druidDataSource.setMaxWait(Long.parseLong(properties.getProperty("maxWait")));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Connection getConnection() throws SQLException {
        return druidDataSource.getConnection();
    }

    public static int update(String sql, Object... params) {
        PreparedStatement ps = null;
        Connection con = null;
        try {
            con = getConnection();
            ps = con.prepareStatement(sql);
            setParams(ps, params);
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(null, ps, con);
        }
        return -1;
    }

    public static int insertAndReturnPrimaryKey(String sql, Object... params) {
        PreparedStatement ps = null;
        Connection con = null;
        ResultSet rs = null;
        try {
            con = getConnection();
            ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            setParams(ps, params);
            ps.executeUpdate();
            rs = ps.getGeneratedKeys();
            while (rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(rs, ps, con);
        }
        return -1;
    }

    public static List<Map> query(String sql, Object... params) {
        List<Map> list = new ArrayList<>();
        PreparedStatement ps = null;
        Connection con = null;
        ResultSet rs = null;
        try {
            con = getConnection();
            ps = con.prepareStatement(sql);
            setParams(ps, params);
            rs = ps.executeQuery();
            ResultSetMetaData rd = rs.getMetaData();
            int count = rd.getColumnCount();
            while (rs.next()) {
                Map<Object, Object> map = new HashMap<>(32);
                for (int i = 0; i < count; i++) {
                    map.put(rd.getColumnLabel(i+1),rs.getObject(i+1));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(rs, ps, con);
        }
        return list;
    }


    private static void setParams(PreparedStatement ps, Object... params) throws SQLException {
        if (params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
        }
    }

    private static void closeAll(ResultSet rs, Statement st, Connection con) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
